package com.stupidzhe.vbreview.controller.stu;

import com.stupidzhe.vbreview.bean.ResultBean;
import com.stupidzhe.vbreview.cache.CaptchaCache;
import com.stupidzhe.vbreview.domain.Class;
import com.stupidzhe.vbreview.domain.Student;
import com.stupidzhe.vbreview.domain.Teacher;
import com.stupidzhe.vbreview.service.ClassService;
import com.stupidzhe.vbreview.service.StudentService;
import com.stupidzhe.vbreview.service.TeacherBaseService;
import com.stupidzhe.vbreview.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

import static com.stupidzhe.vbreview.constant.ProjectConst.HOST;

@Controller
@RequestMapping("/stu")
public class StudentBaseController {

    private final CaptchaCache captchaCache;
    private final StudentService studentService;
    private final ClassService classService;
    private final TeacherBaseService teacherBaseService;

    @Autowired
    public StudentBaseController(CaptchaCache captchaCache, StudentService studentService, ClassService classService, TeacherBaseService teacherBaseService) {
        this.captchaCache = captchaCache;
        this.studentService = studentService;
        this.classService = classService;
        this.teacherBaseService = teacherBaseService;
    }

    /**
     * 主页
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String mainView(HttpServletRequest request, Model model) {
        Student student = (Student) request.getAttribute("student");
        Class c = classService.selectClass(student.getClassId());
        model.addAttribute("c", c);
        model.addAttribute("student", student);
        return "stu/stu.index";
    }

    /**
     * 登录页
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginView() {
        return "stu/stu.login";
    }

    /**
     * 登录页
     */
    @RequestMapping(value = "/home", method = RequestMethod.GET, headers = "Referer=" + HOST + "/stu/")
    public String homeView() {
        return "stu/stu.home";
    }

    /**
     * 登录操作
     * @param number
     * @param password
     * @param captcha
     * @param request
     * @param response
     * @return 执行结果
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResultBean login(@RequestParam(value = "number", required = false)String number,
                            @RequestParam(value = "password", required = false)String password,
                            @RequestParam(value = "captcha", required = false)String captcha,
                            HttpServletRequest request, HttpServletResponse response) {
        String realCaptcha = captchaCache.getCaptcha(request.getSession().getId());
        captchaCache.removeCaptcha(request.getSession().getId());
        if (realCaptcha == null) {
            return new ResultBean(false, "验证码过期，请刷新验证码");
        }
        if (!realCaptcha.equalsIgnoreCase(captcha)) {
            System.out.println(captcha + ":" + realCaptcha);
            return new ResultBean(false, "验证码错误");
        }
        if (null == number || 5 > number.length()) {
            return new ResultBean(false, "用户或密码错误");
        }
        if (null == password || 6 > password.length()) {
            return new ResultBean(false, "用户或密码错误");
        }
        String res = studentService.login(number, password, request);
        if (!"".equals(res)) {
            // cookie格式: account|md5(account)
            Cookie cookie = new Cookie("s_cookie", number + "|" + res);
            cookie.setMaxAge(86400);
            cookie.setPath("/");
            cookie.setDomain("");
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
            return new ResultBean(true, "登录成功");
        }
        return new ResultBean(false, "账号或密码错误");
    }

    /**
     * 注册页
     */
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String registerView(Model model) {
        List<Teacher> teachers = teacherBaseService.getTeachers();
        model.addAttribute("teachers", teachers);
        return "stu/stu.register";
    }

    @ResponseBody
    @RequestMapping(value = "/register/class/{teacherId}", method = RequestMethod.GET)
    public List<Class> registerView(@PathVariable(value = "teacherId")Integer teacherId) {
        return classService.getClassByTeacherId(teacherId);
    }

    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ResultBean register(@RequestParam(value = "number")String number, @RequestParam("name")String name,
                               @RequestParam(value = "pwd")String pwd, @RequestParam(value = "verifiedPwd")String verifiedPwd,
                               @RequestParam(value = "teacherId")Integer teacherId, @RequestParam(value = "classId")Integer classId,
                               @RequestParam(value = "captcha")String captcha, HttpServletRequest request) {
        String realCaptcha = captchaCache.getCaptcha(request.getSession().getId());
        captchaCache.removeCaptcha(request.getSession().getId());
        if (number.trim().equals("") || name.trim().equals("") || pwd.trim().equals("") ||
                verifiedPwd.trim().equals("") || captcha.trim().equals("")) {
            return new ResultBean(false, "输入不能为空");
        }
        if (!realCaptcha.equalsIgnoreCase(captcha)) {
            System.out.println(captcha + ":" + realCaptcha);
            return new ResultBean(false, "验证码错误");
        }
        if (!pwd.equals(verifiedPwd)) {
            return new ResultBean(false, "两次密码不一致");
        }
        return studentService.register(number, name, pwd, teacherId, classId);
    }

    @RequestMapping(value = "/status/check")
    public String checkView() {
        return "stu/stu.check";
    }

    @ResponseBody
    @RequestMapping(value = "/logout", method = RequestMethod.DELETE)
    public ResultBean logout(HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = CookieUtil.getCookieByName(request, "s_cookie");
        if (cookie == null) {
            return new ResultBean(true);
        }
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return new ResultBean(true);
    }

}
